<template>
	<view class="page">
		<view class="h30"></view>
		<view class="h30"></view>
		<view class="flex-SB" @click="showCal = true" style="width: 280rpx;margin: 0 auto;color: #1D6EFA;font-size: 28rpx;">
			<u-icon color="#1D6EFA" name="arrow-left"></u-icon>
			<view>{{dateTime}}</view>
			<u-icon color="#1D6EFA" name="arrow-right"></u-icon>
		</view>
<!-- 		<view class="h30"></view>
		<view class="blocks" style="border-radius: 0;">
			<view v-if="showEchart" class="chart-box">
				<view style="width: 655rpx;height: 550rpx;font-size: 36rpx;line-height: 550rpx;text-align: center;font-weight: bold;">
					{{result.title}}
				</view>
				<view style="text-align: center;color: #8c8c8c;padding: 20rpx 0;">{{ecgTime}}</view>
				<view>
					
				</view>
			</view>
			<view v-else class="blocks" style="height: 550rpx;display: flex;align-items: center;justify-content: center;color: #ccc;">
				暂无数据
			</view>
		</view> -->
		<view class="h30"></view>
		<view class="blocks flex-SB" style="height: 120rpx;background: #fff;">
			<view class="itme-txt">{{result.title||'暂无数据'}}</view>
			<view class="itme-txt">{{ecgTime}}</view>
		</view>
		<view class="h30"></view>
		<view class="blocks flex-SB" style="height: 120rpx;background: #fff;line-height: 120rpx;">
			<view class="itme-txt">静息心率</view>
			<view class="itme-txt">{{hr}}/次</view>
		</view>
		<view class="h30"></view>
<!-- 		<view class="blocks flex-SB" style="height: 120rpx;background: #fff;line-height: 120rpx;">
			<view class="itme-txt">心脏健康</view>
			<view class="itme-txt">{{formatRes(result)}}</view>
		</view> -->
		<view v-if="result.title!=''" class="blocks" style="background: #fff;display: flex;flex-direction: column;">
			<view style="padding: 15rpx;">
				<!-- <view class="res-title">{{result.title}}</view> -->
				<view class="res-txt" :class="{restitle:idx==0}" v-for="(item,idx) in result.dec" :key="idx">{{item}}</view>
				<view class="res-txt" :class="{restitle:idx==0}" v-for="(item,idx) in result.reason" :key="idx">{{item}}</view>
				<view class="res-txt" :class="{restitle:idx==0}" v-for="(item,idx) in result.sugesstion" :key="idx">{{item}}</view>
			</view>
		</view>
		<view class="h30"></view>
		<u-popup :show="showCal">
			<uni-calendar class="uni-calendar--hook" :endDate="maxDate" :showMonth="false" @change="datechange" />
		</u-popup>
	</view>
</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
	import {
		mapState
	} from 'vuex';
	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	let date = d.getDate();
	date = date < 10 ? `0${date}` : date;
	export default {
		computed: {
			...mapState(['member'])
		},
		components: {
			LEchart,
		},
		data() {
			return {
				ecgTime:'',
				hr: '-',
				showCal: false,
				// showEchart: false,
				showEchart: true,
				dateTime: `${year}-${month}-${date}`,
				maxDate: `${year}-${month}-${date}`,
				minDate: `${year}-${month}-${date-100}`,
				nowData: null,
				result:{
						title:"",
						dec:[],
						reason:[],
						sugesstion:[]
					}
			};
		},
		onLoad(opt) {
			let {
				dateTime
			} = opt;
			this.dateTime = dateTime;
			// this.dateTime = "2025-06-24";
			this.initPage(this.dateTime);
		},
		onReady() {
			// this.initPage(this.dateTime);
		},
		methods: {
			formatRes(idx){
				if(idx===""){
					return {
						title:"",
						dec:[],
						reason:[],
						sugesstion:[]
					};
				}
				if(idx===0){
					return {
						title:"无结果 / 有干扰 / 数据异常",
						dec:[" 情况描述：","检测过程中信号质量不足，未能获得有效心率或心律结果。"],
						reason:["可能原因：","佩戴松动、皮肤干燥或有汗水、毛发较多导致电极接触不良。","测试环境干扰（如强电磁波、身体剧烈运动）。","设备传感器或电池异常。"],
						sugesstion:["建议：","检查佩戴位置与紧密度，保持皮肤清洁干燥。","避免运动和强干扰环境下测量。","若多次出现异常，考虑设备校准或送修。"]
						};
				}
				if(idx===1){
					return {
						title:"窦性心率",
						dec:["情况描述："," 心脏由窦房结正常起搏，心律规则，心率在60~100次/分之间。"],
						reason:[],
						sugesstion:["建议：","保持健康生活方式，定期检查即可。"],
					};
				}
				if(idx===2){
					return {
						title:"窦性心率缓",
						dec:["情况描述：","心率 <60 次/分。运动员或安静状态下常见。"],
						reason:["可能原因：","睡眠、运动训练、药物影响、甲状腺功能减退或传导阻滞。"],
						sugesstion:["建议：","无症状者通常无需处理。","若伴随头晕、乏力，应就医心电图检查。"],
					};
				}
				if(idx===3){
					return {
						title:"窦性心率速（窦性心动过速）",
						dec:["情况描述：","心率 >100 次/分，心律规则"],
						reason:["可能原因：","运动、咖啡因、紧张、发热、贫血、甲亢。"],
						sugesstion:["建议：","避免过度刺激。","静息时心率持续过快或伴症状，应就医。"],
					};
				}
				if(idx===4){
					return {
						title:"心率不起（早搏）",
						dec:["情况描述：","出现提前的心搏，常被感知为“心跳漏了一下”。"],
						reason:[" 可能原因：","疲劳、压力、咖啡因、酒精，也可见于心脏病。"],
						sugesstion:["建议：","生活规律，避免刺激。","若频繁或伴症状，做24小时动态心电图。"],
					};
				}
				if(idx===5){
					return {
						title:"心率不起（房颤，心房颤动）",
						dec:["情况描述：","心跳不规则、快慢不一。可无明显症状，也可有心悸或气促。"],
						reason:["风险：","中风、血栓形成。"],
						sugesstion:["建议：","尽快就医，确认是否需抗凝治疗。","长期监测与复查。"],
					};
				}
				if(idx===6){
					return {
						title:"心率过速（室上性心动过速，SVT）",
						dec:["情况描述：","心率突然加快，通常>150 次/分，可伴心悸、胸闷。"],
						reason:["可能原因：","房室结折返、房性心动过速。"],
						sugesstion:["建议：","若发作短暂，可记录并观察。"," 若持续或伴晕厥，应立即就医。","医生可指导迷走神经刺激法"]
					};
				}
			},
			initPage(dateTime) {
				if(this.$refs.tiredChartDetails){
					this.$refs.tiredChartDetails.dispose()
				}
				this.hr = '-';
				if(!this.member.imei){
					return this.$toast("请登录后查看您的数据！");
				};
				uni.$u.http.post('/client/watch_health_data/type', { 
					imei: this.member.imei,
					type:7,
					date:dateTime
				}).then(res => {
					if(res.status == 500){
						return this.$toast(res.msg||'获取数据失败！');
					}
					// this.result = res.data.result;
					// console.log(res.data);
					this.result = this.formatRes(res.data.result);
					if(res.status!=200) return;
					this.showEchart = false;
					let date = [];
					let ecgarr = [];
					if (res.data.value) {
						ecgarr = res.data.value;
						if (ecgarr.length) {
							this.showEchart = true;
							// let initdata = ecgarr;
							let initdata = [];
							// for(let i in ecgarr){
							// 	let evals = Math.abs(ecgarr[i]) - Math.abs(res.data.avgEcg);
							// 	initdata.push(evals)
							// }
							for (let i in ecgarr) {
								// date.push(i)
								if (res.data.direction == -1) {
									initdata.push(ecgarr[i]);
									// initdata.push(0-ecgarr[i]);
								} else {
									// initdata.push(ecgarr[i]);
									initdata.push(Math.abs(ecgarr[i]));
								}
							}
							let avgint = 0;
							if (res.data.direction == -1) {
								avgint = parseInt(res.data.avgEcg);
							}else{
								avgint = Math.abs(parseInt(res.data.avgEcg))
							}
							// console.log(initdata);
							// this.initEcgChart(initdata, date,avgint);
						}
						this.hr = res.data.hr;
						this.ecgTime = res.data.data_time;
					}
				});
			},
			datechange(e){
				this.showCal = false;
				let dstr = e.fulldate;
				if(this.dateTime == dstr){
					return;
				}
				this.dateTime = dstr;
				this.initPage(this.dateTime);
			},
			initEcgChart(data, date,avg) {
				// console.log(avg);
				function func(x) {
					x /= 10;
					return Math.sin(x) * Math.cos(x * 2 + 1) * Math.sin(x * 3 + 2) * 50-10;
				}
				function generateData() {
					let data = [];
					for (let i = -50; i <= 20; i += 0.1) {
						data.push([i, func(i)]);
					}
					return data;
				}
				let option = {
					animation: false,
					grid: {
						top: 2,
						left: 0,
						right: 0,
						bottom: 0
					},
					xAxis: {
						show: false,
						type: 'category',
						axisLabel: {
							show: false
						}
					},
					yAxis: {
						// show: false,
						type: 'value',
						min: avg-3000,
						max: avg+3000,
						// axisLabel: {
						// 	show: false
						// }
					},
					series: [{
						type: 'line',
						showSymbol: false,
						itemStyle: {
							shadowBlur: {
								shadowColor: 'rgba(255, 70, 131, 1)',
								shadowBlur: 1120,
								shadowOffsetY: -2
							},
							color: 'rgb(255, 70, 131)'
						},
						lineStyle: {
							shadowColor: 'rgb(255, 77, 49)',
							shadowBlur: 7.5,
							shadowOffsetX: 0,
							shadowOffsetY: 6
						},
						// data: generateData()
						data
					}]
				};
				this.$nextTick(() => {
					this.$refs.tiredChartDetails.init(echarts, chart => {
						chart.setOption(option);
					});
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.blocks {
		width: 655rpx;
	}
	.itme-txt{
		padding: 0 20rpx;
	}
	.res-txt{
		font-size: 28rpx;
		line-height: 46rpx;
		color: #505050;
	}
	// .res-title{
	// 	font-size: 36rpx;
	// 	line-height: 56rpx;
	// }
	.restitle{
		margin-top: 10rpx;
		color: #000;
		font-size: 36rpx;
		font-weight: 600;
	}
</style>